﻿using System.IO;
using UnityEngine;

namespace TinyAsset
{
    public class ResourceManager : MonoSingleton<ResourceManager>
    {
        public Manifest CurrentManifest { get; private set; }

        AssetSystem AssetSystem = new AssetSystem();

        public void Initialize()
        {
            if (AssetBundleUtility.kUseAssetDatabase == false)
            {
                byte[] bytes = FileHelper.ReadAllBytes(AssetBundleUtility.kManifest);
                if (bytes != null)
                {
                    using (MemoryStream stream = new MemoryStream(bytes))
                    {
                        using (BinaryReader reader = new BinaryReader(stream))
                        {
                            var profile = new Manifest();
                            profile.Deserialize(reader);
                            SetCurrentManifest(profile);
                        }
                    }
                }
            }
        }

        void Update()
        {
            AssetSystem.Update(Time.deltaTime, Time.unscaledDeltaTime);
        }

        public void SetCurrentManifest(Manifest manifest)
        {
            CurrentManifest = manifest;
            AssetSystem.SetCurrentManifest(manifest);
        }

        public AssetOperationHandle LoadAsset<T>(string path) where T : Object
        {
            return AssetSystem.LoadAsset(path, typeof(T));
        }

        public AssetOperationHandle LoadAssetAsync<T>(string path) where T : Object
        {
            return AssetSystem.LoadAssetAsync(path, typeof(T));
        }

        public AssetOperationHandle LoadScene(string path, bool additive)
        {
            return AssetSystem.LoadScene(path, additive);
        }

        public AssetOperationHandle LoadSceneAsync(string path, bool additive)
        {
            return AssetSystem.LoadSceneAsync(path, additive);
        }

        public byte[] ReadAllBytes(string path)
        {
            return FileHelper.ReadAllBytes(path);
        }

        public string ReadAllText(string path)
        {
            return FileHelper.ReadAllText(path);
        }

        public void UnloadAsset(string key)
        {
            AssetSystem.UnloadAsset(key);
        }

        public void UnloadUnusedAssets()
        {
            Resources.UnloadUnusedAssets();
        }
    }
}